var CT = require('./modules/country-list');
var AM = require('./modules/account-manager');
var EM = require('./modules/email-dispatcher');
var SM = require('./modules/search-manager');
var ot = require('./modules/outline-tool.js');
var UIM = require('./modules/upload-image-manager.js');
var PM = require('./modules/publish-manager.js')

module.exports = function (app) {

    // leon tao

    app.get('/', function (req, res) {
        res.redirect('/index');
    });

    // //介绍页面
    // app.get('/index', function (req, res) {
    //     res.render('index');
    // });

    // main page //
    app.get('/index', function (req, res) {
        // check if the user's credentials are saved in a cookie
        if (req.cookies.user == undefined || req.cookies.pass == undefined) {
            res.render('index');
        } else {
            // 自动登录
            AM.autoLogin(req.cookies.nameEmail, req.cookies.pass, function (o) {
                if (o != null) {
                    req.session.user = o;
                    res.redirect('/home');
                } else {
                    // res.render('login', { title: 'Hello - Please Login To Your Account' });
                    res.render('index');
                }
            });
        }
    });


    //在index页面处理用户登录请求。 注意可以用户名或者邮箱登录
    app.post('/index', function (req, res) {
        console.log(' --- login --- ');
        //用户名或者邮箱
        var nameEmail = req.body['name-email'];
        var pass = req.body['pass'];
        console.log('name-email', nameEmail);
        AM.manualLogin(nameEmail, pass, function (returnMsg) {
            if (returnMsg['code'] == 0) {
                res.status(400).send(returnMsg['msg']);
            } else {
                user = returnMsg['user'];
                req.session.user = user;
                res.cookie('nameEmail', user.email, {maxAge: 900000});
                res.cookie('pass', user.pass, {maxAge: 900000});
                res.cookie('name', user.name, {maxAge: 900000});
                res.status(200).send(returnMsg['msg']);
            }
        });
    });


    //注销登录
    app.post('/logout', function (req, res) {
        res.clearCookie('nameEmail');
        res.clearCookie('user');
        res.clearCookie('pass');
        // req.session.user = null;
        req.session.destroy(function (e) {
            res.status(200).send('ok');
        });
    });


    //个人用户页面注册请求, 区分各种不同的用户。如果是申请： 0 - 申请中， 1 - 申请成功， 2 - 申请失败
    app.post('/person-signup', function (req, res) {
        console.log(' --- person-signup --- ');
        //获取用户角色
        var role = req.body['role'];
        newData = {};
        //共同信息
        newData['role'] = role; //区分不同用户
        newData['name'] = req.body['name'];
        newData['pass'] = req.body['pass'];
        newData['email'] = req.body['email'];
        newData['date'] = moment().unix();
        // if(role === 'normal'){ //普通用户
        //
        // }else
        if (role === 'doctor-expert') {//医生/专家有的信息
            console.log('role: doctor-expert');
            newData['order'] = parseInt(req.body['order'], 0); //级别
            newData['section'] = parseInt(req.body['section'], 0); //科室
            newData['medical-age'] = parseInt(req.body['medical-age'], 0); //医龄
            newData['license'] = req.body['license']; //证件图片
            //需要申请
            newData['status'] = 0; //默认申请中

        } else {

        }
        console.log('--- newData ---', newData);

        AM.addNewAccount(newData, function (returnMsg) {
            res.status(200).send(returnMsg);
            // if (returnMsg['code'] === 0) {
            //     res.status(200).send(returnMsg);
            // } else {
            //     //转到主页
            //     // res.redirect('/index#login');
            //     res.status(200).send(returnMsg);
            // }
        });

    });


    // logged-in user homepage 分别返回不同的页面， 个人用户， 医生，机构， 管理员，出版社
    app.get('/home', function (req, res) {
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            var role = req.session.user.role;
            console.log('--- role --- ' + role);

            //默认普通用户
            if (role === 'undefined' || role === undefined)
                role = 'normal';

            var renderModel = 'home' + '-' + role;

            console.log('--- renderModel --- ', renderModel);

            //获取第一级目录
            ot.getOutline(function (outline) {
                res.render(renderModel, {
                    "outline": outline
                });
            });
        }
    });
    //

    //子目录
    app.get('/sub-outline', function (req, res) {
        if (req.session.user == null) {
            // if user is not logged-in redirect back to login page //
            res.redirect('/index');
        } else {
            //获取子目录目录
            var category = String(req.query["category"]);
            if (category === 'undefined' || String(category) === '') {
                res.redirect('/home');
            } else {
                var selections = category.split('>');
                console.log('selections -- ' + selections);
                ot.getSubOutlie(selections, function (result) {
                    if (result['type'] == 0) { //进行搜索
                        //搜索， 跳转到病理页面页面
                        res.redirect('/image-retrieval-list');
                    } else { //返回子目录
                        res.render("sub-outline", {"subOutline": result['subOutline']});
                    }
                });
            }


        }
    });


    //搜索
    function searchToTidy(data) {
        items = ["disease_name", "dept", "modality", "age", "gender", "physician", "location", "character", "images"]
        var tidy = [];
        data.forEach(function (element, index) {
            tidy[index] = {};
            tidy[index]['_id'] = element['_id'];
            items.forEach(function (item) {
                tidy[index][item] = element['_source'][item];

                if (item === "images") {
                    var images = element['_source'][item];
                    var src = images[index % 2]; //img/img.jpg
                    tidy[index]['img'] = "/img/" + src;
                }
            })
        });
        return tidy;
        //
    }

    //image-retrieval-list 影像检索(进入检索列表页面)
    app.get('/image-retrieval-list', function (req, res) {
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            //获取用户检索结果
            var query = String(req.query['search']);
            //在这里应该解析用户的检索条件

            //检索
            if (query === 'undefined' || query === '') {
                SM.searchAll(0, 10, function (res2) {
                    //返回页面
                    if (res2.id === 1) { //成功
                        var list = searchToTidy(res2.hits);
                        res.render('image-retrieval-list', {
                            list: list,
                            from: res2['from'],
                            pages: res2['pages']
                        });
                    }
                });

            } else {
                console.log('--- image-retrieval-list ---', query)
                var search = {"query": query};
                SM.search(search, 0, 10, function (res2) {
                    console.log('--- res ---', res2.hits);
                    //返回页面
                    if (res2.id === 1) { //成功
                        var list = searchToTidy(res2.hits);
                        res.render('image-retrieval-list', {
                            list: list,
                            from: res2['from'],
                            pages: res2['pages']
                        });
                    }
                });

            }
        }
    });

    //病例详情页面
    app.get('/case-detail', function (req, res) {
        console.log('--- image-detail ---');
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            res.render("case-detail");
        }
    });


    //dicom 展示页面
    app.get('/dicom-papaya', function (req, res) {
        console.log('--- dicom-papaya ---');
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            res.render("dicom-papaya");
        }
    });


    //病例上传页面 request response
    app.get('/case-upload', function (req, res) {
        console.log('--- case-upload ---');
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            res.render("case-upload");
        }
    });

    app.get('/publish', function (req, res) {

        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            res.render('publish');
        }

    });

    app.post('/publish', function (req, res) {
        // PM.
    });


    //保存上传图片
    app.post('/image-upload', function (req, res) {
        console.log('--- image-upload ---');
        //保存图片
        UIM.saveUserImage(req, res);
    });

    //删除上传图片
    app.post('/image-delete', function (req, res) {
        console.log('--- image-delete ---');
        //保存图片
        UIM.deleteImage(req, res);
    });


    //个人用户注册
    app.get('/person-signup', function (req, res) {
        console.log('--- personal_signup ---');
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            res.render("person-signup");
        }


    });

    //机构用户注册
    app.get('/organization-signup', function (req, res) {
        console.log('--- organization_signup ---')
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            res.render("organization-signup");
        }


    });


    // 用户管理页面
    app.get('/user-management', function (req, res) {
        console.log('--- user-management ---')
        if (req.session.user == null) {
            res.redirect('/index');
        } else {
            res.render("user-management");
        }


    });


    /// end leon tao


    //忘记密码
    // password reset //
    app.post('/lost-password', function (req, res) {
        // look up the user's account via their email //
        AM.getAccountByEmail(req.body['email'], function (o) {
            if (o) {
                EM.dispatchResetPasswordLink(o, function (e, m) {
                    // this callback takes a moment to return //
                    // TODO add an ajax loader to give user feedback //
                    if (!e) {
                        res.status(200).send('ok');
                    } else {
                        for (k in e) console.log('ERROR : ', k, e[k]);
                        res.status(400).send('unable to dispatch password reset');
                    }
                });
            } else {
                res.status(400).send('email-not-found');
            }
        });
    });

    //重置密码
    app.get('/reset-password', function (req, res) {
        var email = req.query["e"];
        var passH = req.query["p"];
        AM.validateResetLink(email, passH, function (e) {
            if (e != 'ok') {
                res.redirect('/index');
            } else {
                // save the user's email in a session instead of sending to the client //
                req.session.reset = {email: email, passHash: passH};
                res.render('reset', {title: 'Reset Password'});
            }
        })
    });


    app.post('/reset-password', function (req, res) {
        var nPass = req.body['pass'];
        // retrieve the user's email from the session to lookup their account and reset password //
        var email = req.session.reset.email;
        // destory the session immediately after retrieving the stored email //
        req.session.destroy();
        AM.updatePassword(email, nPass, function (e, o) {
            if (o) {
                res.status(200).send('ok');
            } else {
                res.status(400).send('unable to update password');
            }
        })
    });


    app.post('/delete', function (req, res) {
        AM.deleteAccount(req.body.id, function (e, obj) {
            if (!e) {
                res.clearCookie('user');
                res.clearCookie('pass');
                req.session.destroy(function (e) {
                    res.status(200).send('ok');
                });
            } else {
                res.status(400).send('record not found');
            }
        });
    });

    //错误页面
    app.get('/404', function (req, res) {
        res.render('404', {title: 'Page Not Found'});
    });

    app.get('*', function (req, res) {
        res.render('404', {title: 'Page Not Found'});
    });

};
